package cn.sh.library.gmwx.common;

import org.ontoware.rdf2go.RDF2Go;
import org.ontoware.rdf2go.impl.jena.ModelImplJena;
import org.ontoware.rdf2go.model.Model;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Liuyi on 2015/3/20.
 */
public class ModelManager {

    private static ThreadLocal<Map<com.hp.hpl.jena.rdf.model.Model, Model>> threadLocal = new ThreadLocal<>();

    static {
        RDF2Go.register(new org.ontoware.rdf2go.impl.jena.ModelFactoryImpl());
    }

    public static Model get(com.hp.hpl.jena.rdf.model.Model m){
        Map<com.hp.hpl.jena.rdf.model.Model, Model> map = threadLocal.get();

        if( map == null ){
            map = new HashMap<>();
            threadLocal.set(map);
        }
        Model model = map.get(m);

        if( model == null ){
            model = new ModelImplJena(m);
            model.open();
            map.put(m, model);
        } else {
            if (!model.isOpen()) {
                model.open();
            }
        }

        return model;
    }

    public static void close(com.hp.hpl.jena.rdf.model.Model m){
        Map<com.hp.hpl.jena.rdf.model.Model, Model> map = threadLocal.get();
        if( map == null ) return ;
        Model model = map.get(m);
        model.close();
    }

    public static void closeAll(){
        Map<com.hp.hpl.jena.rdf.model.Model, Model> map = threadLocal.get();
        if(map == null) return;
        for(Model model : map.values()){
            model.close();
        }
    }
}
